package com.etc.common;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.session.data.redis.RedisOperationsSessionRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Component
public class MyRoleInterceptor implements HandlerInterceptor {
     private static final Logger logger = LoggerFactory.getLogger(MyRoleInterceptor.class.getName());
     @Autowired
     RedisOperationsSessionRepository repo;
    @Autowired
    RestTemplate restTemplate;
	 @Override
	 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
	    if (handler instanceof HandlerMethod) {
//	        try {
	            if (!checkrole(request, response)) {
	                
	                return false;
	            }
//	        } catch (Exception e) {
//	            return false;
//	        }
	     
	    	Method method = ((HandlerMethod) handler).getMethod();
	    	//如果没被@MyLimit注解修饰
	    	if (!method.isAnnotationPresent(CheckRole.class)) {
	    		return true;
	    		}
	    	CheckRole myLimit = method.getAnnotation(CheckRole.class);
	    	if (myLimit == null) {
	    		return true;
	    		}
	    	String stringVal = myLimit.role();
	    	
				
	    	return false;
	     }
	    return true;
	 }
	
	private boolean checkrole(HttpServletRequest request, HttpServletResponse response) {
	    HttpHeaders headers = new HttpHeaders();
        List<String> cookies =new ArrayList<String>();
        /* 登录获取Cookie 这里是直接给Cookie，可使用下方的login方法拿到Cookie给入*/
        
        cookies.add(request.getHeader(HttpHeaders.COOKIE));       //在 header 中存入cookies
        headers.put(HttpHeaders.COOKIE,cookies);        //将cookie存入头部
        headers.add(HttpHeaders.AUTHORIZATION, request.getHeader(HttpHeaders.AUTHORIZATION));
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        Map map = new HashMap();
        if (request.getParameter("token") != null) {
            map.put("token", request.getParameter("token"));
        }
        // form fangshi
//        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();      //请求体给予内容
//        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
        ObjectMapper om = new ObjectMapper();
        HttpEntity<String> formEntity;
        try {
            formEntity = new HttpEntity<String>(om.writeValueAsString(map), headers);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return false;
        }
        
        ResponseEntity<CodeMessage> resp = restTemplate.postForEntity("http://SERVICE-USER-CENTER/tasks/1", formEntity, CodeMessage.class);
        logger.debug(String.valueOf(resp.getBody()));  
        CodeMessage cm = resp.getBody();
        
        if (cm.getCode() == (Code.SUCESS)) {
            return true;
        } else {
            returnJson(response, cm);
            return false;    
        }
        
	    
    }
	private void returnJson(HttpServletResponse response, CodeMessage cm){
	    ObjectMapper om = new ObjectMapper();
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("appliction/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(om.writeValueAsString(cm));
            writer.flush();
        } catch (IOException e) {
        } finally {
            if (writer != null)
                writer.close();
        }
	}
    @Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
	}
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {
	}
}